package com.clhbolg.aop;

import com.clhbolg.annotation.AccessLimit;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.ServletUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Author cailinhu
 * @Description TODO
 * @Date 2023/3/1 16:19
 * @Version 1.0
 */
@Aspect
@Component
public class AccessLimitAspect {

    @Autowired
    RedisTemplate redisTemplate;


    @Before("@annotation(controllerAccessLimit)")
    public void before(JoinPoint joinPoint, AccessLimit controllerAccessLimit) {
        String name = joinPoint.getSignature().getName();
        //获取注解上的值
        int second = controllerAccessLimit.second();//时间
        int maxCount = controllerAccessLimit.maxCount();//最大尝试次数
        String ip = ServletUtils.getClientIP(ServletUtils.getRequest());//获得ip地址
        String key = ip + "_" + name;
        Long count = redisTemplate.opsForValue().increment(key, 1);
        if (count != null && count == 1) {
            redisTemplate.expire(key, second, TimeUnit.SECONDS);
        }
        if (count>maxCount){
            throw new GlobalException("请求过于频繁，" + second + "秒后再试");
        }
    }


}
